/*/////////////////////////////////////////////////////////////////////////////
//           Version 23.08.2012
//
//  purposes:  Create a log file of parameters saved inside of spectra
//
//  Parameters saved:                       Explanation
//          FileNumber                   :     
//          StartTime                    : Time spectra began to accumulate
//          StopTime                     : Start time of the last added spectra in a .std file
//          SZA                          : Solar Zenith Angle           
//          Lat                          : Latitude
//          Long                         : Longitude
//          Altitude                     : Altitude
//          ElevationAngle               : ElevationAngle -- where the spectrometer *should* be looking
//          NumScans                     : Number of Scans added together
//          NumCounts_MotorOutOfPosition : How many cycles was the motor outside of acceptable range during this file
//          NumCounts_ExposureTimeReset  : How many times did the Exposure need to reset because it was too low/high  
//  
// 
//      Always update SpectraFolder, LogFileName by hand.
//
///////////////////////////////////////////////////////////////////////////////
// by Eric Gentry
// questions: Tilman.Hueneke@iup.uni-heidelberg.de
//            egentry@mit.edu
/////////////////////////////////////////////////////////////////////////////*/

import System;
import System.IO
import DoasCore;
import DoasCore.Spectra;
import DoasCore.IO;
import DoasCore.Script;
import DoasCore.HMI;

    var SpectraFolder = "D:\\TACTS\\2012_08_17_OP_TACTS\\UV1\\spectra_corrected_calibrated_SOLAR"
        //Example:      "D:\\TACTS\\2012_08_17_OP_TACTS\\VIS4\\spectra_corrected_calibrated_SOLAR"
        
    var LogFileName   = "Spectra_Log_Info.txt"

//*****************************************************************************************// 

function main()
{

    var afn : AutoFileName   = new AutoFileName();
        afn.BasePath           = SpectraFolder;
        afn.Prefix             = "M";
        afn.Suffix             = ".std";
        afn.NumberOfDigits     = 6;
        afn.Mode               = "Manual";
        afn.FindFirstIndex();

    var di = new DirectoryInfo(SpectraFolder.substring(0, SpectraFolder.lastIndexOf("\\") +1) + "ScriptOutput\\")
    if(!di.Exists)
          {di.Create()}

    var logFileName    = SpectraFolder.substring(0, SpectraFolder.lastIndexOf("\\") +1) + "ScriptOutput\\" + LogFileName  //Places log file *above* folder of corrected files
    var dispFileSystem = new ActiveXObject("Scripting.FileSystemObject");
    var outfile        = dispFileSystem.OpenTextFile(logFileName,2, true);
        
        outfile.WriteLine("FileNumber\t" + "Start Time\t" + "Stop Time\t" + "SZA\t" + "Latitude\t" + "Longitude\t" + "Altitude\t" + "ElevationAngle\t" + "NumScans\t" + "NumCounts_MotorOutOfPosition\t" + "NumCounts_ExposureTimeReset\t" + "SaturationPercent");
    
    var MeasSpec : ISpectrum  = Specbar.GetSpectrum("Measurement Spectrum");
        MeasSpec.Name         = "Measurement Spectrum";
       
    var TemporaryObject = new Object()
  
    for(var count = 1; afn.Open(MeasSpec) && !Script.StopAllScripts; count++)
   {
        TemporaryObject = ReadTextFile(MeasSpec.FileName)
  
        var FileNumber                   = count    
        var StartTime                    = MeasSpec.StartTime
		    var StartTimeMS					         = TemporaryObject.StartTimeMS
	     	var StopTime				           	 = MeasSpec.StopTime
		    var StopTimeMS					         = TemporaryObject.StopTimeMS
        var SZA                          = MeasSpec.ScanGeometry.SZA
        var Lat                          = MeasSpec.ScanGeometry.Latitude
        var Long                         = MeasSpec.ScanGeometry.Longitude
        var Altitude                     = MeasSpec.Altitude
        var ElevationAngle               = MeasSpec.ElevationAngle
        var NumScans                     = MeasSpec.NumScans
        var Max                          = MeasSpec.Max
        var NumCounts_MotorOutOfPosition = TemporaryObject.NumCounts_MotorOutOfPosition
        var NumCounts_ExposureTimeReset  = TemporaryObject.NumCounts_ExposureTimeReset                          
           
        var SaturationPercent            = Max / (NumScans * 65536) * 100    //In percent
        

       outfile.WriteLine(FileNumber + "\t"  + StartTime + StartTimeMS + "\t" + StopTime + StopTimeMS + "\t" + SZA + "\t" + Lat + "\t" + Long + "\t" + Altitude + "\t" + ElevationAngle + "\t" + NumScans + "\t" + NumCounts_MotorOutOfPosition + "\t" + NumCounts_ExposureTimeReset + "\t" + SaturationPercent);
  }
  
  outfile.Close()
 
 Console.WriteLine("Script: 'ExtractSpectraParameters' finished!") 
}

//*****************************************************************************************// 

function ReadTextFile(InputFile)
{
//  Uses an ActiveX object to give JavaScript the ability to read a text file
//  All lines are read in. Important information is filtered out by description of line (eg: "Timezone:")
//  Returns an Object

     var ShortName      = InputFile.substring(InputFile.lastIndexOf("\\") +1)       // eg. "M001331.std"
     Console.WriteLine("File: " + ShortName)
  
     var ReadFileSystem   = new ActiveXObject("Scripting.FileSystemObject")
     var infile           = ReadFileSystem.GetFile(InputFile)
     var infileStream     = infile.OpenAsTextStream(1, 0)

     var OutputObject     = new Object()
     var TempLine         = ""
     
     var NumScans         = -1
   
    while(!infileStream.AtEndOfStream)
     {  
        TempLine = infileStream.ReadLine().replace("\"", "");  //read and strip " character
           
             if (TempLine.indexOf("No of telescopes out of position") != -1)
                 OutputObject.NumCounts_MotorOutOfPosition = parseInt(TempLine.split("= ")[1])
                 
        else if (TempLine.indexOf("No of exposure time resets")       != -1)
                 OutputObject.NumCounts_ExposureTimeReset  = parseInt(TempLine.split("= ")[1])
                 
		    else if (TempLine.indexOf("Begin of scan ms") != -1)
			           OutputObject.StartTimeMS = TempLine.split("= 0")[1]
			           
	     	else if (TempLine.indexOf("End of scan ms") != -1)
			           OutputObject.StopTimeMS = TempLine.split("= 0")[1]	                 		           
			     
     } 
     
     infileStream.Close()    
     
     return OutputObject 
}  

 //*****************************************************************************************// 
  
main()